<!--
 * @Author: AuroCaffe 18509564594@163.com
 * @Date: 2025-05-24 11:49:05
 * @LastEditors: AuroCaffe 18509564594@163.com
 * @LastEditTime: 2025-08-06 15:41:45
 * @FilePath: \HuiLin\pages\tabBar\cart.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
	<view style="background-color: #fff;position: relative;" :style="{...pageStyle}">
		<headerSlot :propsColor="'#fff'">
			<template v-slot:header>
				<view class="header_slot flex justify-start align-center">
					<view class="flex align-center justify-between  text-black" style="width: 100%;">
						<view class="index_top_image">
							<image :src="`${config.commonUrl}/logo-orange.png`" mode=""></image>
						</view>
						<view class="content text-bold">
							购物车
						</view>
						<view style="width: 20%;"></view>
					</view>
				</view>
			</template>
		</headerSlot>
		<view class="address-bar flex align-center" @click="chooseAddress">
			<text class="cuIcon-locationfill address-icon"></text>
			<view class="address-info">
				<view v-if="addressObj">
					<text class="address-user">{{ addressObj.name || '' }}</text>
					<text class="address-phone">{{ addressObj.phone || '' }}</text>
				</view>
				<view class="address-text">
					{{ addressObj ? (addressObj.fullAddress || '') : (address || '请选择收货地址') }}
				</view>
			</view>
			<text class="cuIcon-right"></text>
		</view>
		<view class="" style="overflow-y: scroll;"
			:style="{paddingBottom: cartListData.length > 0 ? (barHeight + cartBarHeight)+'px' : '0px'}">
			<!-- 空购物车状态 -->
			<view v-if="cartListData.length === 0" class="empty-cart">
				<view class="empty-cart-icon">🛒</view>
				<view class="empty-cart-text">购物车空空如也</view>
				<view class="empty-cart-tip">快去挑选心仪的商品吧</view>
				<view class="empty-cart-btn" @click="goShopping">去购物</view>
			</view>

			<!-- 购物车商品列表 -->
			<CartItem v-else ref='cartItemRef' :cartListData='cartListData' @updataGoods="updataGoods"
				@update-selection="handleUpdateSelection" @update-Delivery="handleDeliveryService"
				@deleteItem="deleteItem" :systemDeliveryServiceFee="systemDeliveryServiceFee"></CartItem>
		</view>

		<!-- 购物车底部栏 - 只在有商品时显示 -->
		<view v-if="cartListData.length > 0" class="cart_bar " id="" :style="{bottom:(barHeight-10)+'px'}">
			<view class="flex align-center">
				<view class="" style="white-space: nowrap;">全选</view>
				<radio @click="handleSelectAll" :class="isSelected?'checked':''" :checked="isSelected" value="A"
					style="transform: scale(0.7);">
				</radio>
			</view>
			<view class="cart-bar-info">
				<view class="cart-bar-total flex align-center">
					<text style="white-space: nowrap;">合计：</text>
					<text class="cart-bar-total-price">￥{{multiShopTotalAmount.toFixed(2)}}</text>
				</view>
				<view class="cart-bar-extra-row flex justify-between align-center">
					<text v-if="deliveryServiceFee" class="cart-bar-fee">含跑腿费: {{deliveryServiceFee}} 元</text>
					<text v-if="price>0" class="cart-bar-detail" @click="changeDetails">明细<text
							class="cuIcon-right"></text></text>
				</view>
			</view>
			<view class="cart-bar-pay-btn payment_btn" :class="{disabled: !canPay()}" @click="showPaymentPopup">
				{{ getButtonText() }}
			</view>
		</view>
		<uni-popup ref="popup" type="center" background-color="#fff">
			<view class="order-detail-popup">
				<!-- 弹窗头部 -->
				<view class="popup-header">
					<text class="popup-title">订单明细</text>
					<text class="popup-close" @click="closeDetails">×</text>
				</view>

				<!-- 弹窗内容 -->
				<view class="popup-content">
					<view class="shop-section" v-for="(goodsInfo, cartIdx) in cartListData"
						:key="goodsInfo.shop._id || cartIdx">
						<template v-if="goodsInfo.shop.isSelected">
							<!-- 店铺信息 -->
							<view class="shop-header">
								<text class="shop-icon">🏪</text>
								<text class="shop-name">{{goodsInfo.shop.name}}</text>
							</view>

							<!-- 商品列表 -->
							<view class="goods-list">
								<view class="goods-item" v-for="(goodsItem, index) in goodsInfo.items"
									:key="goodsItem._id || index">
									<template v-if="goodsItem.isSelected">
										<view class="goods-info">
											<view class="goods-name">{{goodsItem.product.name}}</view>
											<view class="goods-quantity">×{{goodsItem.quantity}}</view>
										</view>

										<view class="price-details">
											<view class="price-row" v-if="goodsItem.product.isSpecialOffer">
												<text class="price-label">原价</text>
												<text
													class="price-value original-price">¥{{goodsItem.product.originalPrice}}</text>
											</view>
											<view class="price-row">
												<text class="price-label">现价</text>
												<text class="price-value current-price">
													¥{{goodsItem.product.displayPrice || goodsItem.product.currentPrice || goodsItem.product.price}}
												</text>
											</view>
											<view class="price-row">
												<text class="price-label">小计</text>
												<text
													class="price-value subtotal-price">¥{{finalPrice(goodsItem).toFixed(2)}}</text>
											</view>
										</view>
									</template>
								</view>
							</view>

							<!-- 店铺费用 -->
							<view class="shop-fees" v-if="goodsInfo.deliveryService">
								<view class="fee-row">
									<text class="fee-label">跑腿费</text>
									<text class="fee-value">¥{{systemDeliveryServiceFee}}</text>
								</view>
							</view>

							<!-- 店铺合计 -->
							<view class="shop-total">
								<text class="total-label">店铺合计</text>
								<text class="total-value">
									¥{{(getShopTotal(goodsInfo) + (goodsInfo.deliveryService ? Number(systemDeliveryServiceFee) : 0)).toFixed(2)}}
								</text>
							</view>
						</template>
					</view>

					<!-- 总计 -->
					<view class="grand-total">
						<text class="grand-total-label">总计</text>
						<text class="grand-total-value">¥{{multiShopTotalAmount.toFixed(2)}}</text>
					</view>
				</view>
			</view>
		</uni-popup>

		<PaymentPopup ref="paymentPopup" :amount="multiShopTotalAmount" @confirm="handlePaymentConfirm"
			:paddingBottom="barHeight" />

		<TabBar :PageCur="'cart'" @height-change="handleBarHeightChange" />
	</view>
</template>

<script>
	import storage from "@/utils/storage.js";
	import {
		getCartList,
		deleteGoods,
		updateCartItem,
		clearCart
	} from "@/api/cart.js";
	import {
		errorHandler
	} from '@/utils/errorHandler.js';
	import ProductOrderPayment from '@/utils/ProductOrderPayment.js';
	import {
		getPlatformInfo
	} from "@/api/members.js"
	import PaymentPopup from '@/components/payment--popup.vue'
	import headerSlot from '@/components/header-slot.vue';
	import CartItem from '@/components/--cart--item.vue';
	import TabBar from '@/components/tabBar.vue';
	import config from '@/config/config';
	import {
		createOrder
	} from '@/api/order.js'; // 假设有此接口
	export default {
		components: {
			headerSlot,
			CartItem,
			TabBar,
			PaymentPopup
		},
		data() {
			return {
				config,
				isSelected: false,
				cartListData: [],
				price: 0,
				barHeight: 50, // 初始值需与组件默认高度一致
				windowHeight: 0,
				cartBarHeight: 0,
				deliveryServiceFee: 0, //跑腿费合计
				systemDeliveryServiceFee: 0, //系统设置跑腿费
				address: '', // 新增收货地址
				addressObj: null,
				addressId: '', //收货地址id
				paymentHandler: new ProductOrderPayment(), // 商品订单支付处理器
				isPaying: false, // 是否正在支付
				isPolling: false, // 是否正在轮询支付状态
				cartUpdateTrigger: 0, // 用于触发计算属性重新计算的触发器
				isPageActive: true, // 页面是否活跃
				currentPollTimer: null // 当前轮询定时器
			}
		},
		onLoad() {
			this.initCart()
			this.getDeliveryServiceFee()
			this.loadAddress()
		},
		onShow() {
			this.isPageActive = true;
			this.loadAddress()
			// 清除购物车角标
			this.$store.commit('setCartCount', 0)
		},
		onHide() {
			this.isPageActive = false;
			// 停止当前轮询
			if (this.currentPollTimer) {
				clearTimeout(this.currentPollTimer);
				this.currentPollTimer = null;
			}
		},
		onUnload() {
			// 页面卸载时清理定时器
			if (this.currentPollTimer) {
				clearTimeout(this.currentPollTimer);
				this.currentPollTimer = null;
			}
		},
		mounted() {
			// 页面渲染后自动计算初始高度
			this.getWindowHeight()
			this.calculateBarHeight()
		},
		computed: {
			pageStyle() {
				return {
					height: `${this.windowHeight}px`,
					paddingBottom: `${this.barHeight}px`
				}
			},
			// 计算多店铺订单总金额 - 改为计算属性，自动响应数据变化
			multiShopTotalAmount() {
				// 添加触发器依赖，确保数量变化时重新计算
				this.cartUpdateTrigger;

				// 直接从 cartListData 计算，确保使用最新的数量数据
				let total = 0;
				
				this.cartListData.forEach(shop => {
					// 只计算有选中商品的店铺
					const selectedItems = shop.items.filter(item => item.isSelected);
					if (selectedItems.length === 0) return;
					
					// 计算店铺商品总价
					const shopTotal = selectedItems.reduce((shopTotal, item) => {
						const price = item.product.currentPrice ||
							(item.product.isSpecialOffer ? item.product.specialPrice : item.product.price);
						// 确保数量是数字类型
						const quantity = parseInt(item.quantity) || 0;
						const itemTotal = price * quantity;
		
						return shopTotal + itemTotal;
					}, 0);
					
					// 加上跑腿费
					const deliveryFee = shop.deliveryService ? this.systemDeliveryServiceFee : 0;
					
					total += shopTotal + deliveryFee;
	
				});


				// 使用 toFixed(2) 确保精度，然后转换为数字
				return Number(total.toFixed(2));
			}
		},
		methods: {
			showPaymentPopup() {
				if (!this.canPay()) {
					if (!this.addressId) {
						uni.showToast({
							title: "请选择收货地址",
							icon: "none"
						});
					} else if (!this.hasSelectedGoods()) {
						uni.showToast({
							title: "请选择要结算的商品",
							icon: "none"
						});
					} else if (this.price <= 0) {
						uni.showToast({
							title: "无支付金额",
							icon: "error",
						});
					}
					return;
				}
				this.$refs.paymentPopup.openPopup()
			},
			async getDeliveryServiceFee() {
				try {
					const res = await getPlatformInfo("deliveryServiceFee");
					if (res.data.code === 200) {
						this.systemDeliveryServiceFee = res.data.data.value;
					} else {
						console.warn('获取跑腿费失败:', res.data.message);
						this.systemDeliveryServiceFee = 0;
					}
				} catch (error) {
					console.error('获取跑腿费失败:', error);
					this.systemDeliveryServiceFee = 0;
				}
			},
			//计算单个商品价格
			finalPrice(goodsItem) {
				// 使用 currentPrice 字段进行计算，如果不存在则回退到原有逻辑
				const currentPrice = goodsItem.product.currentPrice ||
					(goodsItem.product.isSpecialOffer ? goodsItem.product.specialPrice : goodsItem.product.price);
				const total = currentPrice * goodsItem.quantity;
				return Number(total.toFixed(2));
			},
			// 更新购物车商品数量
			async updataGoods(data) {
				try {
					// 查找对应的商品信息
					const cartItem = this.findCartItemById(data.cartId);
					if (!cartItem) {
						throw new Error('商品不存在');
					}

					// 验证库存
					if (data.num > cartItem.product.stock) {
						uni.showToast({
							title: '数量超出库存',
							icon: 'none'
						});
						return;
					}

					// 先更新本地状态，提供即时反馈
					this.updateCartItemQuantity(data.cartId, data.num);

					uni.showLoading({
						title: '更新中...'
					});
					const res = await updateCartItem(data);

					if (res.data.code === 200) {
						// 确保本地状态与服务器状态一致
						this.updateCartItemQuantity(res.data.data._id, res.data.data.quantity);
						
						// 强制触发计算属性重新计算
						this.$nextTick(() => {
							// 重新计算价格和跑腿费
							this.recalculateCart();
							// 更新购物车角标数量
							this.updateCartBadge();
						});

						uni.showToast({
							title: '更新成功',
							icon: 'success'
						});
					} else {
						// 处理业务错误，显示详细错误信息
						const errorMessage = res.data.message || '更新失败';
						uni.showToast({
							title: errorMessage,
							icon: 'none'
						});
						// 更新失败时，回滚本地状态
						this.updateCartItemQuantity(data.cartId, cartItem.quantity);
						return; // 不抛出错误，避免进入catch块
					}
				} catch (error) {
					console.error('更新购物车失败:', error);
					// 使用统一的错误处理
					errorHandler.showApiError(error, '更新失败');
					// 更新失败时，回滚本地状态
					const cartItem = this.findCartItemById(data.cartId);
					if (cartItem) {
						this.updateCartItemQuantity(data.cartId, cartItem.quantity);
					}
				} finally {
					uni.hideLoading();
				}
			},

			/**
			 * 更新购物车商品数量（本地状态）
			 */
			updateCartItemQuantity(goodsId, quantity) {
				let updated = false;
				this.cartListData.forEach(shop => {
					shop.items.forEach(item => {
						if (item._id === goodsId) {
							// 使用 $set 确保响应式更新
							this.$set(item, 'quantity', quantity);
							updated = true;
		
						}
					});
				});
				
				// 只有在实际更新了数据时才触发重新计算
				if (updated) {
					// 触发计算属性重新计算
					this.cartUpdateTrigger++;
					// 强制更新视图
					this.$forceUpdate();
					
					// 确保计算属性立即重新计算
					this.$nextTick(() => {
						// 手动触发计算属性重新计算
						this.cartUpdateTrigger++;
		
					});
				}
			},

			/**
			 * 重新计算购物车总价和跑腿费
			 */
			recalculateCart() {
				this.price = this.totalPrice();
				this.updataCart(); // 重新计算跑腿费
				
				// 确保计算属性重新计算
				this.cartUpdateTrigger++;
			},
			async handlePaymentConfirm(payload) {
				try {
					this.isPaying = true;
					uni.showLoading({
						mask: true,
						title: "创建订单中..."
					});

					// 1. 构建多店铺订单数据
					const multiShopOrderData = this.buildMultiShopOrderData();

					// 2. 创建多店铺订单并支付
					const result = await this.paymentHandler.createMultiShopOrderAndPay(multiShopOrderData);

					uni.hideLoading();

					// 3. 调起微信支付
					// 使用第一个订单的shopId作为支付状态查询的标识
					const outTradeNo = result.outTradeNo;
					await this.callWechatPay(result.wxPayParams, outTradeNo);

				} catch (error) {
					console.error('支付失败:', error);
					uni.hideLoading();
					uni.showToast({
						title: error.message || "支付失败",
						icon: "error"
					});
				} finally {
					this.isPaying = false;
				}
			},
			/**
			 * 构建多店铺订单数据
			 */
			buildMultiShopOrderData() {
				const selectedShops = this.getSelectedShops();

				// 如果没有选中的店铺，抛出错误
				if (selectedShops.shops.length === 0) {
					throw new Error('没有选中的商品');
				}

				// 构建多店铺订单数据
				const shops = selectedShops.shops.map(shop => {
					// 查找对应的购物车店铺数据
					const cartShop = this.cartListData.find(cartShop => cartShop.shop._id === shop.shopId);
					if (!cartShop) {
						throw new Error(`找不到店铺: ${shop.shopId}`);
					}

					// 判断该店铺是否需要送货上门服务
					const addDeliveryService = cartShop.deliveryService;
					const deliveryServiceFee = addDeliveryService ? this.systemDeliveryServiceFee : 0;

					return {
						shopId: shop.shopId,
						items: shop.items.map(item => ({
							productId: item.productId,
							quantity: item.quantity
						})),
						addDeliveryService: addDeliveryService,
						deliveryServiceFee: deliveryServiceFee
					};
				});

				return {
					shops: shops,
					address: this.addressObj,
					openid: this.paymentHandler.getUserOpenid()
				};
			},

			/**
			 * 查找购物车商品项
			 */
			findCartItem(productId) {
				// 如果没有商品，返回null
				if (this.cartListData.length === 0) {
					return null;
				}

				for (const shop of this.cartListData) {
					const item = shop.items.find(item => item.product._id === productId);
					if (item) return item;
				}
				return null;
			},

			/**
			 * 根据购物车ID查找商品项
			 */
			findCartItemById(cartId) {
				for (const shop of this.cartListData) {
					const item = shop.items.find(item => item._id === cartId);
					if (item) return item;
				}
				return null;
			},

			/**
			 * 调起微信支付
			 */
			callWechatPay(wxPayParams, outTradeNo) {
				return new Promise((resolve, reject) => {
					wx.requestPayment({
						...wxPayParams,
						success: () => {
							// 支付成功，开始查询支付状态
							this.startPaymentStatusQuery(outTradeNo);
							resolve();
						},
						fail: (err) => {
							reject(new Error('支付失败'));
						}
					});
				});
			},

			/**
			 * 开始查询支付状态
			 */
			startPaymentStatusQuery(outTradeNo) {
				this.isPolling = true;
				uni.showLoading({
					mask: true,
					title: "查询支付状态中..."
				});

				// 使用多店铺订单支付状态查询
				this.startMultiShopPaymentPolling(outTradeNo);
			},

			/**
			 * 开始多店铺订单支付状态轮询
			 */
			startMultiShopPaymentPolling(outTradeNo) {
				let attempts = 0;
				const maxAttempts = 20;
				const interval = 3000;
				let pollTimer = null;

				const poll = async () => {
					// 如果页面不活跃，停止轮询
					if (!this.isPageActive) {
						this.isPolling = false;
						uni.hideLoading();
						return;
					}

					try {
						attempts++;
						const result = await this.paymentHandler.queryMultiShopOrderPayment(outTradeNo);

						if (result.wechatTradeState === 'SUCCESS') {
							// 支付成功
							this.isPolling = false;
							uni.hideLoading();
							uni.showToast({
								title: "支付成功！",
								icon: "success"
							});

							// 清空购物车
							this.clearSelectedCartItems();

							// 跳转到订单页面
							uni.redirectTo({
								url: "/pages/mePages/samOrder"
							});
							return;
						} else if (result.wechatTradeState === 'CLOSED') {
							// 订单关闭
							this.isPolling = false;
							uni.hideLoading();
							uni.showToast({
								title: "订单已关闭",
								icon: "error"
							});
							return;
						} else if (result.wechatTradeState === 'NOTPAY') {
							// 未支付，继续轮询
							if (attempts < maxAttempts) {
								pollTimer = setTimeout(poll, interval);
							} else {
								this.isPolling = false;
								uni.hideLoading();
								uni.showToast({
									title: "支付状态查询超时，请稍后手动检查",
									icon: "none"
								});
							}
						}
					} catch (error) {
						console.error('轮询查询失败:', error);
						if (attempts < maxAttempts) {
							pollTimer = setTimeout(poll, interval);
						} else {
							this.isPolling = false;
							uni.hideLoading();
							uni.showToast({
								title: error.message || "支付失败",
								icon: "error"
							});
						}
					}
				};

				// 开始第一次轮询
				pollTimer = setTimeout(poll, interval);

				// 保存定时器引用，用于清理
				this.currentPollTimer = pollTimer;
			},

			/**
			 * 清空已选中的购物车商品
			 */
			clearSelectedCartItems() {
				const selectedProductIds = this.getSelectedGoods().map(item => item.productId);
				if (selectedProductIds.length > 0) {
					clearCart({
						productIds: selectedProductIds
					}).then(() => {
						this.initCart();
						// 支付成功后购物车角标会在initCart中自动更新
					});
				}
			},

			getSelectedShops() {
				// 如果没有商品，返回空数组
				if (this.cartListData.length === 0) {
					return {
						shops: []
					};
				}

				return {
					shops: this.cartListData
						.filter(shop => shop.items.some(item => item.isSelected)) // 只包含有选中商品的店铺
						.map(shop => {
							const selectedItems = shop.items.filter(item => item.isSelected);
							return {
								shopId: shop.shop._id, // 假设cartListData中的店铺对象有shopId属性
								items: selectedItems.map(item => ({
									productId: item.product._id,
									quantity: item.quantity,
									// 可以根据需要添加更多产品信息
								})),
							};
						})
				};
			},
			async initCart() {
				try {
					uni.showLoading({
						title: '加载中...'
					});
					const res = await getCartList();

					if (res.data.code === 200) {
						// 根据新的数据结构，data.data.shops 是数组
						const shopsData = res.data.data.shops || [];

						this.cartListData = shopsData.map(item => ({
							items: item.items.map(res => ({
								...res,
								isSelected: false // 预定义响应式属性
							})),
							shop: {
								...item.shop,
								isSelected: false // 预定义响应式属性
							},
							deliveryService: false
						}));

						// 重置所有状态
						this.resetCartState();

						// 更新购物车角标数量
						this.updateCartBadge();
					} else {
						throw new Error(res.data.message || '加载购物车失败');
					}
				} catch (error) {
					console.error('初始化购物车失败:', error);
					uni.showToast({
						title: error.message || '加载购物车失败',
						icon: 'error'
					});
					// 清空购物车数据
					this.cartListData = [];
					this.resetCartState();
				} finally {
					uni.hideLoading();
				}
			},

			/**
			 * 重置购物车状态
			 */
			resetCartState() {
				this.deliveryServiceFee = 0;
				this.price = 0;
				this.isSelected = false;
			},

			//删除商品二次确认
			async deleteItem(id) {
				uni.showModal({
					title: '确认删除',
					content: '确定要删除该商品吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({
									title: '删除中...'
								});
								const result = await deleteGoods(id);

								if (result.data.code === 200) {
									// 从本地状态中移除商品，保持其他状态
									this.removeCartItem(id);
									// 重新计算价格和跑腿费
									this.recalculateCart();

									// 更新购物车角标数量
									this.updateCartBadge();

									uni.showToast({
										title: "删除成功",
										icon: "success",
									});
								} else {
									throw new Error(result.data.message || '删除失败');
								}
							} catch (error) {
								console.error('删除商品失败:', error);
								uni.showToast({
									title: error.message || '删除失败',
									icon: 'error'
								});
								// 删除失败时重新加载购物车
								this.initCart();
							} finally {
								uni.hideLoading();
							}
						}
					}
				});
			},

			/**
			 * 从本地状态中移除购物车商品
			 */
			removeCartItem(id) {
				this.cartListData.forEach((shop, shopIndex) => {
					const itemIndex = shop.items.findIndex(item => item._id === id);
					if (itemIndex !== -1) {
						// 移除商品
						shop.items.splice(itemIndex, 1);

						// 如果店铺没有商品了，移除整个店铺
						if (shop.items.length === 0) {
							this.cartListData.splice(shopIndex, 1);
						}
					}
				});
			},
			//全选切换
			handleSelectAll() {
				// 如果没有商品，不允许全选操作
				if (this.cartListData.length === 0) {
					return;
				}

				const newStatus = !this.isSelected
				this.cartListData.forEach((cartItem, index) => {
					this.$set(cartItem.shop, 'isSelected', newStatus)
					cartItem.items.forEach(product => {
						this.$set(product, 'isSelected', newStatus)
					})
				})
				// 使用 updataCart 方法来确保跑腿费计算正确
				this.updataCart()
				
				// 强制触发计算属性重新计算
				this.$nextTick(() => {
					this.cartUpdateTrigger++;
				});
			},
			// 总价计算
			totalPrice() {
				// 如果没有商品，返回0
				if (this.cartListData.length === 0) {
					return 0;
				}

				const total = this.cartListData.reduce((total, shop) => {

					return total + shop.items.reduce((shopTotal, item) => {
						if (!item.isSelected) return shopTotal;

						// 获取基础价格，优先使用 currentPrice
						const basePrice = item.product.currentPrice ||
							(item.product.isSpecialOffer ? item.product.specialPrice : item.product.price);
						// 确保数量是数字类型
						const quantity = parseInt(item.quantity) || 0;

						// 普通商品计算
						return shopTotal + (basePrice * quantity);
					}, 0)
				}, 0);

				// 使用 toFixed(2) 确保精度，然后转换为数字
				return Number(total.toFixed(2));
			},
			handleDeliveryService(id) {
				this.cartListData.forEach(cartItem => {
					if (cartItem.shop._id === id) {
						cartItem.deliveryService = !cartItem.deliveryService
					}
				})
				// 使用 updataCart 方法来确保跑腿费计算正确
				this.updataCart()
				
				// 强制触发计算属性重新计算
				this.$nextTick(() => {
					this.cartUpdateTrigger++;
				});
			},
			// 接收子组件更新
			handleUpdateSelection(payload) {
				const {
					shopId,
					productId,
					isSelected
				} = payload
				if (productId) {
					let num = 0
					// 更新单个商品
					this.cartListData.forEach(cartItem => {
						if (cartItem.shop._id === shopId) {
							const product = cartItem.items.forEach(p => {
								if (p._id === productId) {
									p.isSelected = isSelected
								}
								if (p.isSelected) {
									num++
								}
							})
							cartItem.shop.isSelected = num === cartItem.items.length
						}
					})
					// 更新店铺全选状态
					this.updataCart()
				} else {
					// 更新整个店铺
					let num = 0
					this.cartListData.forEach(cartItem => {
						if (cartItem.shop._id === shopId) {
							cartItem.shop.isSelected = isSelected
							cartItem.items.forEach(p => p.isSelected = isSelected)
						}
						if (cartItem.shop.isSelected) {
							num++
						}
					})

					this.updataCart()
				}
				
				// 强制触发计算属性重新计算
				this.$nextTick(() => {
					this.cartUpdateTrigger++;
				});
			},
			//更新购物车选中
			updataCart() {
				let num = 0
				// 重置跑腿费
				this.deliveryServiceFee = 0

				// 如果没有商品，设置全选状态为false
				if (this.cartListData.length === 0) {
					this.isSelected = false;
					this.price = 0;
					return;
				}

				this.cartListData.forEach(cartItem => {
					if (cartItem.shop.isSelected) {
						num++
						// 如果店铺被选中且有跑腿服务，累加跑腿费
						if (cartItem.deliveryService) {
							this.deliveryServiceFee += this.systemDeliveryServiceFee
						}
					}
				})

				this.isSelected = num === this.cartListData.length
				this.price = this.totalPrice()
				
				// 触发计算属性重新计算
				this.cartUpdateTrigger++;
			},
			goPage(route) {
				this.$router.smartNavigate({
					url: route
				})
			},
			closePage() {
				uni.navigateBack()
			},


			changeDetails() {
				this.$refs.popup.open('center')
			},

			closeDetails() {
				this.$refs.popup.close()
			},

			/**
			 * 计算店铺商品总价
			 */
			getShopTotal(goodsInfo) {
				// 如果没有商品，返回0
				if (!goodsInfo || !goodsInfo.items || goodsInfo.items.length === 0) {
					return 0;
				}

				const total = goodsInfo.items.reduce((total, item) => {
					if (!item.isSelected) return total;
					const basePrice = item.product.currentPrice ||
						(item.product.isSpecialOffer ? item.product.specialPrice : item.product.price);
					// 确保数量是数字类型
					const quantity = parseInt(item.quantity) || 0;
					return total + (basePrice * quantity);
				}, 0);

				// 使用 toFixed(2) 确保精度，然后转换为数字
				return Number(total.toFixed(2));
			},

			/**
			 * 获取选中的商品数量
			 */
			getSelectedGoodsCount() {
				// 如果没有商品，返回0
				if (this.cartListData.length === 0) {
					return 0;
				}

				return this.cartListData.reduce((count, shop) => {
					return count + shop.items
						.filter(item => item.isSelected)
						.reduce((shopCount, item) => shopCount + item.quantity, 0);
				}, 0);
			},

			/**
			 * 检查是否有选中的商品
			 */
			hasSelectedGoods() {
				return this.getSelectedGoods().length > 0;
			},

			/**
			 * 检查是否可以支付
			 */
			canPay() {
				return this.address && this.hasSelectedGoods() && !this.isPaying && !this.isPolling;
			},



			/**
			 * 获取多店铺订单统计信息
			 */
			getMultiShopOrderStats() {
				const selectedShops = this.getSelectedShops();
				if (selectedShops.shops.length === 0) {
					return {
						shopCount: 0,
						productCount: 0,
						deliveryShopCount: 0
					};
				}

				let productCount = 0;
				let deliveryShopCount = 0;

				selectedShops.shops.forEach(shop => {
					productCount += shop.items.length;
					const cartShop = this.cartListData.find(cartShop => cartShop.shop._id === shop.shopId);
					if (cartShop && cartShop.deliveryService) {
						deliveryShopCount++;
					}
				});

				return {
					shopCount: selectedShops.shops.length,
					productCount: productCount,
					deliveryShopCount: deliveryShopCount
				};
			},

			/**
			 * 跳转到购物页面
			 */
			goShopping() {
				this.$router.smartNavigate({
					url: '/pages/homePages/sam/samPurchase'
				});
			},
			handleBarHeightChange(height) {
				// 动态设置内容区域底部内边距
				this.barHeight = height + 10
			},

			getWindowHeight() {
				uni.getSystemInfo({
					success: (res) => {
						this.windowHeight = res.windowHeight
					}
				})
			},
			calculateBarHeight() {
				const query = uni.createSelectorQuery().in(this)
				query.select('.cart_bar').boundingClientRect(data => {
					if (data) {
						this.cartBarHeight = data.height

					}
				}).exec()
			},
			chooseAddress() {
				this.$router.smartNavigate({
					url: '/pages/mePages/address/addressManagement?select=1'
				});
			},
			loadAddress() {
				const addr = uni.getStorageSync('selectedAddress');
				if (addr && typeof addr === 'object') {
					this.addressObj = {
						name: addr.name || '',
						phone: addr.phone || '',
						fullAddress: addr.fullAddress || '',
						id: addr.id || ''
					};
					this.address = addr.fullAddress || '';
					this.addressId = addr.id || '';
				} else if (typeof addr === 'string') {
					this.address = addr || '';
					this.addressObj = null;
					this.addressId = '';
				} else {
					this.address = '';
					this.addressObj = null;
					this.addressId = '';
				}
			},
			getSelectedGoods() {
				// 如果没有商品，返回空数组
				if (this.cartListData.length === 0) {
					return [];
				}

				// 返回所有选中的商品 [{productId, quantity, ...}]
				return this.cartListData.flatMap(shop =>
					shop.items.filter(item => item.isSelected).map(item => ({
						productId: item.product._id,
						quantity: item.quantity,
					}))
				);
			},
			/**
			 * 计算购物车总商品数量
			 */
			calculateCartTotalItems() {
				return this.cartListData.reduce((total, shop) => {
					return total + shop.items.reduce((shopTotal, item) => shopTotal + item.quantity, 0);
				}, 0);
			},

			/**
			 * 更新购物车角标
			 */
			updateCartBadge() {
				const totalItems = this.calculateCartTotalItems();
				this.$store.commit('setCartCount', totalItems);
			},

			/**
			 * 获取按钮文本
			 */
			getButtonText() {
				if (this.isPaying) return '支付中...';
				if (this.isPolling) return '查询中...';

				const count = this.getSelectedGoodsCount();
				return count > 0 ? `立即支付 (${count}件)` : '请选择商品';
			},

			toggleSelectAll() {
				const newStatus = !this.isSelected;
				this.cartListData.forEach(cartItem => {
					this.$set(cartItem.shop, 'isSelected', newStatus);
					cartItem.items.forEach(product => {
						this.$set(product, 'isSelected', newStatus);
					});
				});
				this.isSelected = newStatus;
				this.price = this.totalPrice();
			},
		},

	}
</script>

<style lang="scss" scoped>
	.header_slot {
		padding: 0 32rpx;
		width: 100%;
		font-weight: 500;
		font-size: 36rpx;
		color: #2C2622;
	}

	#cartBar {
		padding: 32rpx;
		padding-bottom: 100px;
		background-color: #fff;
	}

	.index_top_image {
		width: 176rpx;
		height: 48rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.cu-item {
		margin: 0;
		border-bottom: 1px solid #eee;
	}

	.shoppingCart_box {
		padding: 12rpx 0;
	}

	.goods_img {
		width: 120rpx;
		height: 120rpx;
		margin-right: 20rpx;
	}

	.goods_img image {
		border-radius: 20rpx;
	}

	.goods_title {
		font-weight: 700;
		font-size: 32rpx;
		color: #000;
		line-height: 40rpx;
	}

	.goods_pire {
		font-weight: 700;
		font-size: 32rpx;
		color: #FF2E44;
		line-height: 46rpx;
	}

	.goods_num {
		width: 100%;
		position: absolute;
		left: 0;
		bottom: 0;
	}

	.count_price,
	.count_buy {
		margin-right: 30rpx;
	}

	.count_price {
		color: red;
	}

	.count_buy {
		color: orange;
		margin-top: 8rpx;
	}

	.payment_btn {
		color: #fff;
		background-color: #f37b1d;
		padding: 12rpx 24rpx;
		border-radius: 20rpx;
	}

	.payment_btn.disabled {
		background: #ccc;
		color: #fff;
		// pointer-events: none;
	}

	.cu-bar.tabbar {
		height: auto;
	}

	.order-detail-popup {
		width: 90vw;
		max-width: 600rpx;
		max-height: 80vh;
		background: #fff;
		border-radius: 24rpx;
		overflow: hidden;
		box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 32rpx;
		border-bottom: 1rpx solid #f0f0f0;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: white;
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: bold;
	}

	.popup-close {
		font-size: 40rpx;
		line-height: 1;
		cursor: pointer;
		padding: 8rpx;
		border-radius: 50%;
		transition: background-color 0.2s;
	}

	.popup-close:hover {
		background-color: rgba(255, 255, 255, 0.1);
	}

	.popup-content {
		max-height: 60vh;
		overflow-y: auto;
		padding: 32rpx;
	}

	.shop-section {
		margin-bottom: 32rpx;
	}

	.shop-header {
		display: flex;
		align-items: center;
		margin-bottom: 24rpx;
		padding: 16rpx 0;
		border-bottom: 2rpx solid #f0f0f0;
	}

	.shop-icon {
		font-size: 32rpx;
		margin-right: 16rpx;
	}

	.shop-name {
		font-size: 28rpx;
		font-weight: bold;
		color: #333;
	}

	.goods-list {
		margin-bottom: 24rpx;
	}

	.goods-item {
		margin-bottom: 24rpx;
		padding: 20rpx;
		background: #f8f9fa;
		border-radius: 12rpx;
	}

	.goods-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16rpx;
	}

	.goods-name {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
		flex: 1;
	}

	.goods-quantity {
		font-size: 24rpx;
		color: #666;
		background: #e9ecef;
		padding: 4rpx 12rpx;
		border-radius: 12rpx;
	}

	.price-details {
		background: white;
		padding: 16rpx;
		border-radius: 8rpx;
	}

	.price-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 8rpx;
	}

	.price-row:last-child {
		margin-bottom: 0;
		border-top: 1rpx solid #f0f0f0;
		padding-top: 8rpx;
		margin-top: 8rpx;
	}

	.price-label {
		font-size: 24rpx;
		color: #666;
	}

	.price-value {
		font-size: 24rpx;
		font-weight: 500;
	}

	.original-price {
		color: #999;
		text-decoration: line-through;
	}

	.current-price {
		color: #ff4757;
	}

	.subtotal-price {
		color: #2ed573;
		font-weight: bold;
	}

	.shop-fees {
		margin-bottom: 16rpx;
		padding: 16rpx;
		background: #fff3cd;
		border-radius: 8rpx;
		border-left: 4rpx solid #ffc107;
	}

	.fee-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.fee-label {
		font-size: 24rpx;
		color: #856404;
	}

	.fee-value {
		font-size: 24rpx;
		color: #856404;
		font-weight: bold;
	}

	.shop-total {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 16rpx 0;
		border-top: 2rpx solid #e9ecef;
	}

	.total-label {
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
	}

	.total-value {
		font-size: 28rpx;
		color: #ff4757;
		font-weight: bold;
	}

	.grand-total {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx 0;
		margin-top: 24rpx;
		border-top: 3rpx solid #ff4757;
		background: #fff5f5;
		padding: 24rpx 16rpx;
		border-radius: 12rpx;
	}

	.grand-total-label {
		font-size: 32rpx;
		color: #333;
		font-weight: bold;
	}

	.grand-total-value {
		font-size: 36rpx;
		color: #ff4757;
		font-weight: bold;
	}

	.empty-cart {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 120rpx 32rpx;
		text-align: center;
	}

	.empty-cart-icon {
		font-size: 120rpx;
		margin-bottom: 32rpx;
		opacity: 0.6;
	}

	.empty-cart-text {
		font-size: 36rpx;
		color: #333;
		font-weight: bold;
		margin-bottom: 16rpx;
	}

	.empty-cart-tip {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 48rpx;
	}

	.empty-cart-btn {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: white;
		padding: 24rpx 48rpx;
		border-radius: 40rpx;
		font-size: 32rpx;
		font-weight: bold;
		cursor: pointer;
		transition: transform 0.2s;
	}

	.empty-cart-btn:active {
		transform: scale(0.95);
	}

	.cart_bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fff;
		padding: 18rpx 24rpx 38rpx 24rpx;
		box-shadow: 0 0 1px 0 #ccc;
		z-index: 10;
		display: flex;
		align-items: center;
	}

	.cart-bar-info {
		flex: 1;
		margin: 0 24rpx;
	}

	.cart-bar-total {
		font-size: 30rpx;
		color: #333;
		margin-bottom: 0;
		margin-top: 2rpx;
		font-weight: 500;
	}

	.cart-bar-total-price {
		color: #e64340;
		font-size: 32rpx;
		font-weight: 800;
		margin-left: 8rpx;
		letter-spacing: 1rpx;
	}

	.cart-bar-extra-row {
		width: 100%;
		margin-top: 6rpx;
		font-size: 24rpx;
		color: #888;
		display: flex;
		justify-content: space-between;
		align-items: center;
		white-space: nowrap;
		overflow: hidden;
	}

	.cart-bar-fee,
	.cart-bar-detail {
		flex: 1;
		text-align: left;
		white-space: nowrap;
	}

	.cart-bar-detail {
		text-align: right;
	}

	.cart-bar-fee {
		color: #fd6e37;
		font-size: 24rpx;
		flex: 1;
		text-align: left;
	}

	.cart-bar-detail {
		color: #888;
		font-size: 24rpx;
		flex: 1;
		text-align: right;
		cursor: pointer;
	}

	.cart-bar-pay-btn {
		color: #fff;
		background-color: #f37b1d;
		padding: 24rpx 32rpx;
		border-radius: 40rpx;
		font-size: 32rpx;
		font-weight: 700;
		text-align: center;
		box-shadow: 0 4rpx 16rpx #fd6e3722;
		transition: background 0.2s;
	}

	.cart-bar-pay-btn.disabled {
		background: #ccc;
		color: #fff;
		// pointer-events: none;
	}

	.address-bar {
		background: #fff7f2;
		padding: 24rpx 32rpx;
		font-size: 30rpx;
		color: #333;
		border-bottom: 1px solid #f0f0f0;
		cursor: pointer;
	}

	.address-icon {
		color: #fd6e37;
		font-size: 36rpx;
		margin-right: 16rpx;
	}

	.address-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		overflow: hidden;
	}

	.address-user,
	.address-phone {
		font-size: 28rpx;
		color: #333;
		margin-right: 24rpx;
	}

	.address-text {
		font-size: 30rpx;
		color: #666;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.cart-bar-checkbox {
		margin-right: 24rpx;
		cursor: pointer;
		user-select: none;
	}

	.cart-bar-checkbox .uni-checkbox {
		margin-right: 12rpx;
		transform: scale(1.2);
	}

	.cart-bar-checkbox .cart-checkbox-label {
		font-size: 30rpx;
		color: #333;
	}
</style>